import 'dart:async';
import 'package:pacsun/model/userModel.dart';
import 'package:intl/intl.dart';
import 'package:flutter/material.dart';
import 'package:pacsun/view/create/sharePage.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:webview_flutter/webview_flutter.dart';

// --------------------------------------------//
import 'package:pacsun/provider/userProv.dart' show UserProvider;
import 'package:pacsun/provider/sysTagsProvider.dart' show SysTagsProvider;
// --------------------------------------------//
import 'package:pacsun/model/sysUserTagModel.dart' show YouAreTagModel;
// --------------------------------------------//
import 'package:pacsun/services/socialMediaConnectService.dart'
    show TikTokConnect;
// --------------------------------------------//
import '../user/userMain.dart' show DividerLine;
import 'package:pacsun/utils/birthdayPicker.dart' show showBirthdayPicker;
import 'package:pacsun/view/user/userMain.dart' show UserMain;
import 'package:pacsun/main.dart' show MainScaffold;
import 'package:pacsun/widgets/toastMenu.dart' show ToastMenu;

// --------------------------------------------//
class BecomeCreatorController {
  final TextEditingController nameController = TextEditingController();
//  final TextEditingController emailController = TextEditingController();
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController dobController = TextEditingController();
  final TextEditingController youAreController = TextEditingController();
  final TextEditingController tiktokController = TextEditingController();
  final TextEditingController instagramController = TextEditingController();
  final TextEditingController youtubeController = TextEditingController();

  List<String> selectedYouAreList = []; // Changed from String? to List<String>

  void dispose() {
    nameController.dispose();
    // emailController.dispose();
    phoneController.dispose();
    dobController.dispose();
    youAreController.dispose();
    tiktokController.dispose();
    instagramController.dispose();
    youtubeController.dispose();
  }

  Map<String, dynamic> toJson() {
    return {
      'name': nameController.text,
      //   'email': emailController.text,
      'phone': phoneController.text,
      'dob': dobController.text.isNotEmpty ? dobController.text : null,
      'youAre': youAreController.text,
      'tiktok': tiktokController.text,
      'instagram': instagramController.text,
      'youtube': youtubeController.text
    };
  }
}

class BecomeCreator extends StatefulWidget {
  final int sourceIndex; // Add this field

  const BecomeCreator({super.key, required this.sourceIndex});

  @override
  State<BecomeCreator> createState() => _BecomeCreatorState();
}

class _BecomeCreatorState extends State<BecomeCreator> {
  final _formKey = GlobalKey<FormState>();
  final _controller = BecomeCreatorController();

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    final currentUser = context.read<UserProvider>().currentUser;

    _controller.nameController.text = currentUser?.nickName ?? '';
    _controller.phoneController.text = currentUser?.phone ?? '';
  }

  /// * when updating social media status to database, please make sure [openId], [mediaType] are associated.
  void _submitForm() async {
    if (_formKey.currentState?.validate() ?? false) {
      final submittedData = _controller.toJson();
      print('submittedData: ${submittedData}');

      final currentUser = context.read<UserProvider>().currentUser;
      if (currentUser != null) {
        // Create a new user model by copying the current one and updating only non-null fields
        final updatedUser = currentUser.copyWith(
          fullName: submittedData['name'] ?? currentUser.fullName,
          email: submittedData['email'] ?? currentUser.email,
          phone: submittedData['phone'] ?? currentUser.phone,
          birthday: submittedData['dob']?.toString() ?? currentUser.birthday,
          youAre: submittedData['youAre'] ?? currentUser.youAre,
          mediaType: submittedData['tiktok'] != ''
              ? 1
              : submittedData['instagram'] != ''
                  ? 2
                  : submittedData['youtube'] != ''
                      ? 3
                      : null,
          openId: submittedData['tiktok'] != ''
              ? submittedData['tiktok']
              : submittedData['instagram'] != ''
                  ? submittedData['instagram']
                  : submittedData['youtube'] != ''
                      ? submittedData['youtube']
                      : null,
          // Add other fields as needed
        );
        print('updatedUser.toJson():  ${updatedUser.toJson()}');

        // Update the user in the provider
        await context
            .read<UserProvider>()
            .registerCreator(context, updatedUser.toJson());

        if (widget.sourceIndex == 2) {
          if (context.read<UserProvider>().currentUser?.userType == 0) {
            // register 'creator' failed
            return;
            //  Navigator.pop(context);
          } else {
            // register 'creator' successfully. and going to creator main page.

            // Navigator.push(
            //   context,
            //   MaterialPageRoute(
            //     builder: (context) => MainScaffold(targetIndex: 2),
            //   ),
            // );
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                builder: (context) => MainScaffold(targetIndex: 2),
              ),
            );

            // Navigator.push(
            //     context,
            //     MaterialPageRoute(
            //         builder: (context) => const CreateCreatorMain()));
            //  Navigator.pushNamed(context, '/create');
          }
        }
        if (widget.sourceIndex == 3) {
          //
          //   Navigator.pushNamed(context, '/me');

          // user from use page and navigator back use page
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => const UserMain()));
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: Colors.black,
      // 防止页面被键盘推上去，让Submit按钮固定在底部
      resizeToAvoidBottomInset: false,
      body: Form(
        key: _formKey,
        child: Stack(
          children: [
            // 第1层：固定背景图 - 独立出来，不影响下面的UI
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Container(
                height: 319.h, // 背景图高度 375*319
                decoration: BoxDecoration(
                  image: DecorationImage(
                    fit: BoxFit.fill,
                    image: AssetImage("assets/imgs/ic_setting_header_bg.png"),
                  ),
                ),
              ),
            ),

            // 第2层：原有的CustomScrollView和SliverAppBar
            GestureDetector(
              // 添加滑动手势检测来关闭键盘
              onPanUpdate: (details) {
                // 如果是垂直滑动且超过一定阈值，关闭键盘
                if (details.delta.dy.abs() > 0.1) {
                  FocusScope.of(context).unfocus();
                }
              },
              child: CustomScrollView(
                physics: BouncingScrollPhysics(),
                slivers: [
                  SliverAppBar(
                    automaticallyImplyLeading: false,
                    leading: SafeArea(
                      child: IconButton(
                        icon: const Icon(Icons.keyboard_backspace,
                            color: Colors.white),
                        onPressed: () => Navigator.pop(context),
                      ),
                    ),
                    expandedHeight: 213.h - MediaQuery.of(context).padding.top,
                    pinned: true,
                    backgroundColor: Colors.transparent, // 透明背景，不遮挡固定背景图
                    collapsedHeight:
                        kToolbarHeight + MediaQuery.of(context).padding.top,
                    flexibleSpace: FlexibleSpaceBar(
                      background: Container(
                        // 移除这里的背景图，因为背景图已经独立出来了
                        color: Colors.transparent,
                      ),
                    ),
                  ),
                  SliverList(
                    delegate: SliverChildListDelegate([
                      Padding(
                        padding: const EdgeInsets.only(
                            left: 10, right: 10, bottom: 6),
                        child: Material(
                          elevation: 4,
                          borderRadius: BorderRadius.circular(12),
                          color: const Color.fromRGBO(17, 17, 17, 1),
                          child: SizedBox(
                            height: 460.h, // 设置稍微高一点的固定高度
                            //height: 510.h, // 设置稍微高一点的固定高度
                            child: Column(
                              children: [
                                _NameField(controller: _controller),
                                const DividerLine(),
                                const _EmailField(),
                                const DividerLine(),
                                _PhoneField(controller: _controller),
                                const DividerLine(),
                                _DateOfBirthField(controller: _controller),
                                const DividerLine(),
                                _TagsField(controller: _controller),
                                const DividerLine(),
                                const SocialMedia(),
                                SizedBox(
                                    height: 4.h), // 减少Social Media到TikTok的间距
                                TikTokLink(controller: _controller),
                                SizedBox(height: 8.h), // 添加14px间距
                                const InsLink(),
                                SizedBox(height: 8.h), // 添加14px间距
                                const YoutubeLink(),
                              ],
                            ),
                          ),
                        ),
                      ),
                      // 固定的底部间距，确保内容可以滚动到Submit按钮上方
                      SizedBox(height: 250.h), // 增加底部间距以确保总是有足够内容触发滚动
                    ]),
                  ),
                ],
              ),
            ),

            // 第3层：Submit按钮始终固定在屏幕底部
            Positioned(
              bottom: 30,
              left: 20,
              right: 20,
              child: SafeArea(
                child: SubmitBtn(onPressed: _submitForm),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// class BecomeHeader extends StatelessWidget {
//   const BecomeHeader({super.key});

//   @override
//   Widget build(BuildContext context) => Column(
//         mainAxisAlignment: MainAxisAlignment.center,
//         children: [
//           const SizedBox(height: 30),
//           Column(
//             mainAxisSize: MainAxisSize.min,
//             children: [
//               Image(
//                 image: AssetImage("assets/imgs/ic_little_rocket.png"),
//                 width: 48.w,
//                 height: 48.h,
//               ),
//               Text(
//                 'BECOME A PACSUN',
//                 textAlign: TextAlign.center,
//                 style: TextStyle(
//                   fontSize: 24,
//                   letterSpacing: 0,
//                   fontFamily: 'Poppins',
//                   fontWeight: FontWeight.w600,
//                   color: const Color.fromRGBO(255, 205, 26, 1),
//                 ),
//                 textScaler: TextScaler.noScaling,
//               ),
//               Row(
//                 mainAxisAlignment: MainAxisAlignment.center,
//                 children: [
//                   Text(
//                     'CREATOR IN 60S',
//                     textAlign: TextAlign.center,
//                     style: TextStyle(
//                       fontSize: 24,
//                       letterSpacing: 0,
//                       fontFamily: 'Poppins',
//                       fontWeight: FontWeight.w600,
//                       color: const Color.fromRGBO(255, 205, 26, 1),
//                     ),
//                     textScaler: TextScaler.noScaling,
//                   ),
//                 ],
//               )
//             ],
//           ),
//           // Add the Row with gradient line and button here
//           const SizedBox(height: 8),
//           // const GradientLine(),
//         ],
//       );
// }

class GradientLine extends StatelessWidget {
  const GradientLine({super.key});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: MediaQuery.of(context).size.width * 0.4,
          height: 1,
          margin: const EdgeInsets.only(right: 10),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [
                Color.fromRGBO(255, 208, 114, 0.2), // Original starting color
                Color(0xFFFF4323).withAlpha(153),
                Color(0xFFFF3800), // More vibrant orange-red
              ],
              stops: [
                0.0,
                0.8,
                1.0
              ], // Most of the gradient focuses on the end color
            ),
          ),
        ),
        SizedBox(
            width: 18,
            height: 18,
            child: Image.asset('assets/icons/icon_rocket.png')),
      ],
    );
  }
}

class _NameField extends StatelessWidget {
  final BecomeCreatorController controller;

  const _NameField({required this.controller});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 55.h,
      child: ListTile(
          leading: Text(
            'Name',
            style: TextStyle(
              fontSize: 16,
              letterSpacing: -0.41,
              fontFamily: 'Poppins',
              fontWeight: FontWeight.w500,
              color: Color.fromRGBO(255, 255, 255, 1),
            ),
          ),
          title: TextFormField(
            controller: controller.nameController,
            textAlign: TextAlign.right,
            cursorColor: Colors.white,
            style: TextStyle(
              fontSize: 12,
              letterSpacing: -0.41,
              fontFamily: 'Poppins',
              fontWeight: FontWeight.w400,
              color: Color.fromRGBO(255, 255, 255, 1),
            ),
            decoration: InputDecoration(
              hintText: 'Please enter your name',
              hintStyle: TextStyle(
                color: Color.fromRGBO(255, 255, 255, 0.3),
              ),
              border: InputBorder.none,
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your name';
              }
              return null;
            },
          ),
          trailing: SizedBox.shrink()),
    );
  }
}

class _EmailField extends StatefulWidget {
  const _EmailField();

  @override
  State<_EmailField> createState() => _EmailFieldState();
}

class _EmailFieldState extends State<_EmailField> {
  final TextEditingController _emailController =
      TextEditingController(); // Initialize properly

  @override
  void initState() {
    super.initState();

    _emailController.text =
        context.read<UserProvider>().currentUser?.email ?? '';
    _emailController.addListener(() {
      if (mounted) setState(() {});
    });
  }

  @override
  void dispose() {
    _emailController.dispose(); // Don't forget to dispose the controller
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 55.h,
      child: ListTile(
        leading: Text(
          'Email',
          style: TextStyle(
            fontSize: 16,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w500,
            color: Color.fromRGBO(255, 255, 255, 1),
          ),
        ),
        title: TextFormField(
          readOnly: true,
          controller: _emailController,
          keyboardType: TextInputType.emailAddress,
          textAlign: TextAlign.right,
          cursorColor: Colors.white,
          style: TextStyle(
            fontSize: 12,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w400,
            color: Color.fromRGBO(255, 255, 255, 1),
          ),
          decoration: InputDecoration(
            hintText: 'Please enter your email',
            hintStyle: TextStyle(
              color: Color.fromRGBO(255, 255, 255, 0.3),
            ),
            border: InputBorder.none,
          ),
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please enter your email';
            }
            if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
              return 'Please enter a valid email';
            }
            return null;
          },
        ),
        trailing: SizedBox.shrink(),
      ),
    );
  }
}

class _PhoneField extends StatefulWidget {
  final BecomeCreatorController controller;

  const _PhoneField({required this.controller});

  @override
  _PhoneFieldState createState() => _PhoneFieldState();
}

class _PhoneFieldState extends State<_PhoneField> {
  late FocusNode _focusNode;
  String? _errorText;

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 55.h,
      child: ListTile(
        dense: true,
        leading: Text(
          'Phone',
          style: TextStyle(
            fontSize: 16,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w500,
            color: Color.fromRGBO(255, 255, 255, 1),
          ),
        ),
        title: TextFormField(
          focusNode: _focusNode,
          controller: widget.controller.phoneController,
          keyboardType: TextInputType.phone,
          textAlign: TextAlign.right,
          cursorColor: Colors.white,
          style: TextStyle(
            fontSize: 12,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w400,
            color: Color.fromRGBO(255, 255, 255, 1),
          ),
          decoration: InputDecoration(
            hintText: 'Please enter your phone number',
            hintStyle: TextStyle(
              color: _errorText != null
                  ? Colors.red
                  : Color.fromRGBO(255, 255, 255, 0.3),
            ),
            border: InputBorder.none,
            // Completely remove error space
            errorBorder: null,
            errorStyle: TextStyle(fontSize: 0, height: 0),
            contentPadding: EdgeInsets.zero, // Adjust if needed
          ),
          validator: (value) {
            if (value == null || value.isEmpty) {
              setState(() => _errorText = 'Please enter your phone number');
              return ''; // Return empty string to trigger validation but show nothing
            }
            setState(() => _errorText = null);
            return null; // Validation passed
          },
          onFieldSubmitted: (_) => _focusNode.unfocus(),
          onTapOutside: (event) => _focusNode.unfocus(),
        ),
        trailing: SizedBox.shrink(),
      ),
    );
  }
}

class _DateOfBirthField extends StatefulWidget {
  final BecomeCreatorController controller;

  const _DateOfBirthField({required this.controller});

  @override
  State<_DateOfBirthField> createState() => _DateOfBirthFieldState();
}

class _DateOfBirthFieldState extends State<_DateOfBirthField> {
  String? _errorText;
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 55.h,
      child: ListTile(
        dense: true,
        leading: Text(
          'Date of Birth',
          style: TextStyle(
            fontSize: 16,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w500,
            color: Color.fromRGBO(255, 255, 255, 1),
          ),
        ),
        title: GestureDetector(
          //  onTap: () => _selectDate(context),
          onTap: () => showBirthdayPicker(
            context: context,
            initialDate: widget.controller.dobController.text.isNotEmpty
                ? DateFormat('MM/dd/yyyy')
                    .parse(widget.controller.dobController.text)
                : DateTime.now(),
            onDateSelected: (selectedDate) => widget.controller.dobController
                .text = DateFormat('MM/dd/yyyy').format(selectedDate),
          ),
          child: AbsorbPointer(
            child: TextFormField(
              controller: widget.controller.dobController,
              textAlign: TextAlign.right,
              cursorColor: Colors.white,
              style: TextStyle(
                fontSize: 12,
                letterSpacing: -0.41,
                fontFamily: 'Poppins',
                fontWeight: FontWeight.w400,
                color: Color.fromRGBO(255, 255, 255, 1),
              ),
              decoration: InputDecoration(
                hintText: 'Please select',
                hintStyle: TextStyle(
                  color: _errorText != null
                      ? Colors.red
                      : Color.fromRGBO(255, 255, 255, 0.3),
                ),
                border: InputBorder.none,
                // Completely remove error space
                errorBorder: null,
                errorStyle: TextStyle(fontSize: 0, height: 0),
                contentPadding: EdgeInsets.zero, // Adjust if needed
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  setState(
                      () => _errorText = 'Please select your date of birth');
                  return ''; // Return empty string to trigger validation but show nothing
                }
                setState(() => _errorText = null);
                return null; // Validation passed
              },
            ),
          ),
        ),
        trailing: Image.asset('assets/icons/icon_forwardArrow.png',
            height: 13, width: 7, color: Colors.white),
      ),
    );
  }
}

class _TagsField extends StatelessWidget {
  final BecomeCreatorController controller;
  const _TagsField({super.key, required this.controller});

  // 将 ID 字符串转换为 name 列表用于显示
  List<String> _convertIdsToNames(String? ids, List<YouAreTagModel> sysTags) {
    if (ids == null || ids.isEmpty) return [];

    List<String> idList =
        ids.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList();
    List<String> names = [];

    for (String idStr in idList) {
      try {
        int id = int.parse(idStr);
        YouAreTagModel? tag = sysTags.firstWhere((tag) => tag.id == id,
            orElse: () => YouAreTagModel(id: -1, name: ''));
        if (tag.id != -1) {
          names.add(tag.name);
        }
      } catch (e) {
        // 忽略无效的 ID
      }
    }

    return names;
  }

  // 将 ID 字符串转换为 ID 列表
  List<int> _convertIdsToList(String? ids) {
    if (ids == null || ids.isEmpty) return [];

    return ids
        .split(',')
        .map((e) => e.trim())
        .where((e) => e.isNotEmpty)
        .map((e) {
          try {
            return int.parse(e);
          } catch (e) {
            return -1;
          }
        })
        .where((id) => id != -1)
        .toList();
  }

  // 将 ID 列表转换为 ID 字符串
  String _convertListToIds(List<int> ids) => ids.join(',');

  Future<void> _showBecomeSelectionModal(BuildContext context) async {
    await showModalBottomSheet(
      context: context,
      backgroundColor: const Color.fromRGBO(34, 34, 34, 1),
      shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(12))),
      isScrollControlled: true,
      builder: (BuildContext context) {
        // 将 selectedIds 移到 StatefulBuilder 外部，避免重复初始化
        List<int> selectedIds =
            _convertIdsToList(context.read<UserProvider>().currentUser?.youAre);

        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return Selector<SysTagsProvider, List<YouAreTagModel>>(
              selector: (_, provider) => provider.sysTags,
              builder: (_, sysTags, __) {
                return Padding(
                  padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom),
                  child: Container(
                    padding:
                        const EdgeInsets.only(left: 16, right: 16, bottom: 38),
                    decoration: const BoxDecoration(
                      color: Color.fromRGBO(34, 34, 34, 1),
                      borderRadius:
                          BorderRadius.vertical(top: Radius.circular(12)),
                    ),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // Header row
                        SizedBox(
                          height: 44,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              IconButton(
                                icon: const Icon(Icons.close,
                                    color: Colors.white, size: 24),
                                onPressed: () => Navigator.pop(context),
                              ),
                              const Text(
                                'Select Tags',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600,
                                  fontFamily: 'Poppins',
                                ),
                              ),
                              Opacity(
                                opacity: selectedIds.isEmpty ? 0.2 : 1.0,
                                child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                    minimumSize: const Size(75, 26),
                                    backgroundColor:
                                        const Color.fromRGBO(215, 48, 48, 1),
                                    shape: RoundedRectangleBorder(
                                        borderRadius:
                                            BorderRadius.circular(25)),
                                    elevation: 0,
                                    padding: EdgeInsets.zero,
                                  ),
                                  onPressed: selectedIds.isEmpty
                                      ? null
                                      : () {
                                          String idsString =
                                              _convertListToIds(selectedIds);
                                          controller.youAreController.text =
                                              idsString;

                                          context
                                              .read<UserProvider>()
                                              .updateUserInfo(
                                                  UserModel(youAre: idsString));

                                          Navigator.pop(context);
                                        },
                                  child: Container(
                                    width: 35,
                                    height: 16,
                                    alignment: Alignment.center,
                                    child: const Text(
                                      'SAVE',
                                      style: TextStyle(
                                        fontFamily: 'Poppins',
                                        fontWeight: FontWeight.w600,
                                        fontSize: 14,
                                        height: 16 / 14,
                                        letterSpacing: -0.41,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),

                        // Divider
                        Container(
                          height: 1,
                          color: const Color.fromRGBO(60, 60, 67, 0.36),
                          margin: const EdgeInsets.only(bottom: 16),
                        ),

                        // Tag selection area
                        Flexible(
                          child: SingleChildScrollView(
                            child: Wrap(
                              spacing: 12,
                              runSpacing: 12,
                              children: sysTags.map((tag) {
                                final isSelected = selectedIds.contains(tag.id);
                                return GestureDetector(
                                  onTap: () {
                                    setState(() {
                                      if (isSelected) {
                                        selectedIds.remove(tag.id);
                                      } else {
                                        selectedIds.add(tag.id);
                                      }
                                    });
                                  },
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 20, vertical: 10),
                                    // constraints:
                                    //     const BoxConstraints(minWidth: 130),
                                    decoration: BoxDecoration(
                                      color: isSelected
                                          ? Colors.white
                                          : const Color.fromRGBO(
                                              99, 99, 99, 0.5),
                                      borderRadius: BorderRadius.circular(30),
                                      border: Border.all(
                                        color: isSelected
                                            ? Colors.transparent
                                            : const Color.fromRGBO(
                                                255, 255, 255, 0.2),
                                        width: 1,
                                      ),
                                    ),
                                    child: Text(
                                      tag.name,
                                      style: TextStyle(
                                          fontFamily: 'Poppins',
                                          fontWeight: FontWeight.w500,
                                          fontSize: 14,
                                          height: 16 / 14,
                                          letterSpacing: -0.41,
                                          color: isSelected
                                              ? Colors.black
                                              : Colors.white),
                                    ),
                                  ),
                                );
                              }).toList(),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 55.h,
      child: ListTile(
        dense: true,
        visualDensity: VisualDensity.compact, // 添加紧凑密度
        minVerticalPadding: 0, // 减少垂直内边距
        leading: const Text(
          "Style Profile",
          style: TextStyle(
            fontSize: 16,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w500,
            color: Color.fromRGBO(255, 255, 255, 1),
          ),
        ),
        title: Selector2<UserProvider, SysTagsProvider, String>(
          selector: (_, userProvider, sysTagsProvider) {
            String? userYouAre = userProvider.currentUser?.youAre;
            List<YouAreTagModel> sysTags = sysTagsProvider.sysTags;

            if (userYouAre != null && userYouAre.isNotEmpty) {
              // 将 ID 字符串转换为 name 列表，然后连接成显示字符串
              List<String> names = _convertIdsToNames(userYouAre, sysTags);
              return names.join(', ');
            }
            return '';
          },
          builder: (context, displayText, child) {
            // 初始化 controller 的值为用户的 youAre ID 字符串
            String? userYouAre =
                context.read<UserProvider>().currentUser?.youAre;
            if (userYouAre != null &&
                controller.youAreController.text.isEmpty) {
              controller.youAreController.text = userYouAre;
            }

            return GestureDetector(
              onTap: () => _showBecomeSelectionModal(context),
              child: AbsorbPointer(
                child: Container(
                  alignment: Alignment.centerRight,
                  child: Text(
                    displayText.isEmpty ? 'Please select' : displayText,
                    style: TextStyle(
                      fontSize: 12,
                      letterSpacing: -0.41,
                      fontFamily: 'Poppins',
                      fontWeight: FontWeight.w400,
                      color: displayText.isEmpty
                          ? const Color.fromRGBO(255, 255, 255, 0.3)
                          : const Color.fromRGBO(255, 255, 255, 1),
                    ),
                    textAlign: TextAlign.right,
                  ),
                ),
              ),
            );
          },
        ),
        trailing: Image.asset('assets/icons/icon_forwardArrow.png',
            height: 13, width: 7, color: Colors.white),
      ),
    );
  }
}

class SocialMedia extends StatelessWidget {
  const SocialMedia({super.key});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      dense: true,
      leading: Text(
        "Social Media",
        style: TextStyle(
          fontSize: 16,
          letterSpacing: -0.41,
          fontFamily: 'Poppins',
          fontWeight: FontWeight.w500,
          color: Color.fromRGBO(255, 255, 255, 1),
        ),
      ),
    );
  }
}

class TikTokLink extends StatelessWidget {
  final BecomeCreatorController controller;
  const TikTokLink({super.key, required this.controller});

  Future<void> _connectTikTok(BuildContext context) async {
    try {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) => const Center(child: CircularProgressIndicator()),
      );

      final oauthUrl = await TikTokConnect().getOauth2SSO();

      // 接收完整的回调URL字符串
      final callbackUrl = await Navigator.of(context).push<String>(
        MaterialPageRoute(
          fullscreenDialog: true,
          builder: (_) => TikTokAuthWebView(initialUrl: oauthUrl),
        ),
      );

      if (callbackUrl != null) {
        // 解析URL获取code
        final uri = Uri.parse(callbackUrl);

        final code = uri.queryParameters['code'];
        final scopes = uri.queryParameters['scopes'];

        if (code != null && scopes != null) {
          final openId =
              await TikTokConnect().exchangeCodeForOpenId(code, scopes);

          if (openId != null) {
            final _tikTokInfo = await TikTokConnect().getUserInfo(openId);

            Navigator.of(context).pop();
            print('Linked tiktok returned info: ${_tikTokInfo}');

            context
                .read<UserProvider>()
                .updateTiktokLinkStatus(context, openId);
          }

          controller.tiktokController.text = openId;

          ToastMenu.showToast(context, 'Linking to TikTok successfully!');

          //  showStoreFrontBottomSheet(context, 'tt');
        } else {
          Navigator.of(context).pop();
          throw Exception('Authorization code not found in callback URL');
        }
      } else {
        Navigator.of(context).pop();
        throw Exception('User canceled or authentication failed');
      }
    } catch (e) {
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        // SnackBar(content: Text('TikTok connection failed: ${e.toString()}')),
        SnackBar(content: Text('TikTok connection failed.')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 25.h,
      child: ListTile(
        horizontalTitleGap: 13,
        dense: true,
        leading: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Image.asset('assets/imgs/img_tiktok.png',
                width: 20, height: 20)),
        title: Text(
          'TikTok',
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 16,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w500,
            color: const Color.fromRGBO(255, 255, 255, 1),
          ),
        ),
        trailing: Selector<UserProvider, bool>(
            selector: (_, provider) =>
                provider.currentUser?.connected?['tiktok'] != null,
            builder: (context, isLinkTiktok, child) {
              // print(
              //     "provider in become:  ${context.read<UserProvider>().currentUser?.connected?['tiktok']}");
              return isLinkTiktok
                  ? Image.asset('assets/icons/icon_green_complete.png',
                      height: 20, width: 20)
                  : SizedBox(
                      height: 25,
                      child: OutlinedButton(
                        // onPressed: () => _connectTikTok(context),
                        onPressed: () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      sharePage(becomeController: controller)));
                        },
                        style: OutlinedButton.styleFrom(
                          side: BorderSide.none,
                          backgroundColor: const Color.fromRGBO(215, 48, 48, 1),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12.5),
                          ),
                        ),
                        child: Text(
                          'Connect',
                          style: TextStyle(
                            fontFamily: 'Poppins',
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            letterSpacing: -0.41,
                            fontSize: 14,
                          ),
                        ),
                      ),
                    );
            }),
      ),
    );
  }
}

class TikTokAuthWebView extends StatefulWidget {
  final String initialUrl;

  const TikTokAuthWebView({super.key, required this.initialUrl});

  @override
  State<TikTokAuthWebView> createState() => _TikTokAuthWebViewState();
}

class _TikTokAuthWebViewState extends State<TikTokAuthWebView> {
  late final WebViewController _controller;
  bool _isLoading = true;
  bool _hasError = false;

  @override
  void initState() {
    super.initState();
    _initializeWebViewController();
  }

  Future<void> _initializeWebViewController() async {
    // 创建基础控制器
    _controller = WebViewController();
    // 通用配置
    _controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.white)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            if (progress == 100) {
              setState(() => _isLoading = false);
            }
          },
          onNavigationRequest: (NavigationRequest request) {
            if (request.url
                .startsWith('https://uat.wind.cma-cgm.com/api/miniapp/oauth')) {
              Navigator.of(context).pop(request.url);
              return NavigationDecision.prevent;
            }
            return NavigationDecision.navigate;
          },
          onWebResourceError: (WebResourceError error) {
            setState(() => _hasError = true);
            debugPrint('WebView Error: ${error.description}');
          },
        ),
      );

    // 清除缓存和Cookies
    await _clearWebViewCacheAndCookies();

    // 加载带时间戳的URL确保全新会话
    final timestampedUrl =
        '${widget.initialUrl}${widget.initialUrl.contains('?') ? '&' : '?'}_t=${DateTime.now().millisecondsSinceEpoch}';
    await _controller.loadRequest(Uri.parse(timestampedUrl));

    // 延迟执行JavaScript清除（确保页面加载完成）
    Future.delayed(const Duration(seconds: 1), _clearWebStorage);
  }

  Future<void> _clearWebViewCacheAndCookies() async {
    try {
      await WebViewCookieManager().clearCookies();
      await _controller.clearCache();
    } catch (e) {
      debugPrint('Failed to clear cache/cookies: $e');
    }
  }

  Future<void> _clearWebStorage() async {
    try {
      await _controller.runJavaScript('''
        try {
          localStorage && localStorage.clear();
          sessionStorage && sessionStorage.clear();
        } catch(e) {
          // 忽略JavaScript错误
        }
      ''');
    } catch (e) {
      debugPrint('Failed to run JavaScript: $e');
    }
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: const Text('Connect TikTok'),
          leading: IconButton(
            icon: const Icon(Icons.close),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ),
        body: Stack(
          children: [
            if (!_hasError)
              WebViewWidget(controller: _controller)
            else
              const Center(
                child: Text('Failed to load TikTok authentication',
                    style: TextStyle(color: Colors.red)),
              ),
            if (_isLoading && !_hasError)
              const Center(child: CircularProgressIndicator()),
          ],
        ),
      );
}

class YoutubeLink extends StatelessWidget {
  const YoutubeLink({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 25.h,
      child: ListTile(
        horizontalTitleGap: 13, // ← Controls spacing between leading and title
        dense: true,
        leading: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Image.asset('assets/imgs/img_youtube.png',
                width: 20, height: 20)),
        title: Text(
          'YouTube',
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 16,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w500,
            color: Color.fromRGBO(255, 255, 255, 1),
          ),
        ),
        trailing: SizedBox(
          height: 25,
          child: OutlinedButton(
            onPressed: () {
              ToastMenu.showToast(context, 'Function under development');
            },
            style: OutlinedButton.styleFrom(
              side: BorderSide.none,
              backgroundColor: Color.fromRGBO(215, 48, 48, 1),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12.5),
              ),
            ),
            child: const Text('Connect',
                style: TextStyle(
                    fontFamily: 'Poppins',
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                    letterSpacing: -0.41,
                    fontSize: 14)),
          ),
        ),
      ),
    );
  }
}

class InsLink extends StatelessWidget {
  const InsLink({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 25.h,
      child: ListTile(
        horizontalTitleGap: 13, // ← Controls spacing between leading and title
        dense: true,
        leading: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child:
                Image.asset('assets/imgs/img_ins.png', width: 20, height: 20)),
        title: Text(
          'Instagram',
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 16,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w500,
            color: Color.fromRGBO(255, 255, 255, 1),
          ),
        ),
        trailing: SizedBox(
          height: 25,
          child: OutlinedButton(
            onPressed: () {
              ToastMenu.showToast(context, 'Function under development');
            },
            style: OutlinedButton.styleFrom(
              side: BorderSide.none,
              backgroundColor: Color.fromRGBO(215, 48, 48, 1),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12.5),
              ),
            ),
            child: const Text('Connect',
                style: TextStyle(
                    fontFamily: 'Poppins',
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                    letterSpacing: -0.41,
                    fontSize: 14)),
          ),
        ),
      ),
    );
  }
}

class SubmitBtn extends StatelessWidget {
  final VoidCallback onPressed;

  const SubmitBtn({super.key, required this.onPressed});

  @override
  Widget build(BuildContext context) => SizedBox(
        width: 335.w,
        height: 55.h,
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
              backgroundColor: const Color.fromRGBO(215, 48, 48, 1),
              padding: EdgeInsets.zero,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(27.5.r))),
          onPressed: onPressed,
          child: Text(
            'SUBMIT',
            style: TextStyle(
              fontFamily: 'Poppins',
              fontWeight: FontWeight.w700,
              fontSize: 20.sp,
              height: 1.0,
              letterSpacing: 0,
              color: Colors.white,
            ),
          ),
        ),
      );
}
